//
// 操作界面 设置相应的窗口按钮等
package cn.drenal.gui;

import cn.drenal.common.Constants;
import cn.drenal.common.Main;
import cn.drenal.helper.JDBCHelper;
import cn.drenal.user.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

public class GuiLogin extends PetGui
{
    private JTextField filedUsername = new JTextField(50);
    private JPasswordField fieldPsw = new JPasswordField(50);

    private JButton btnReg = new JButton("注册");
    private JButton btnLogin = new JButton("登录");

    private JLabel labelGreeting = new JLabel("Welcome");
    private JLabel labelUsername = new JLabel("用户名");
    private JLabel labelPsw = new JLabel("密码");

    private JPanel paneBtn = new JPanel();

    @Override
    public void showGui()
    {

        this.setTitle("宠物商店");
        this.setSize(350, 300);      //设置了行宽列宽
        super.showGui();
    }

    @Override
    protected void addComp()                    //添加一些按钮组件
    {
        setLayout(null);
        //设置相对位置
        labelGreeting.setBounds(78, 10, 200, 100);
        labelGreeting.setFont(new Font(null, 0, 46));
        labelUsername.setBounds(60, 110, 100, 50);
        labelPsw.setBounds(60, 150, 50, 50);
        filedUsername.setBounds(110, 120, 170, 30);
        fieldPsw.setBounds(110, 160, 170, 30);
        paneBtn.setBounds(0, 210, 350, 30);
        //添加组件进panelBtn
        paneBtn.add(btnLogin);
        paneBtn.add(btnReg);
        //添加组件进主窗口
        this.add(labelGreeting);
        this.add(labelUsername);
        this.add(filedUsername);
        this.add(labelPsw);
        this.add(fieldPsw);
        this.add(paneBtn);
    }

    @Override
    protected void addListener()                //监听器
    {
        //给文本框添加监听
        filedUsername.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (e.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    btnLogin.doClick();
                }
            }
        });

        fieldPsw.addKeyListener(new KeyAdapter()
        {
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (e.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    btnLogin.doClick();
                }
            }
        });

        btnReg.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                JTextField username = new JTextField();
                JTextField adminToken = new JTextField();
                JPasswordField password = new JPasswordField();
                JPasswordField passwordConfirm = new JPasswordField();

                Object[] msg =
                        {
                                Constants.USERNAME_TEXT, username,
                                Constants.PASSWORD_TEXT, password,
                                Constants.PASSWORD_CONFIRM_TEXT, passwordConfirm,
                                Constants.ADMIN_TOKEN_TEXT, adminToken
                        };
                //弹出注册窗口
                int option = JOptionPane.showConfirmDialog(null, msg, "注册账号", JOptionPane.OK_CANCEL_OPTION);

                if (option == JOptionPane.OK_OPTION)
                {
                    String dataUsername = username.getText().trim();
                    String dataPsw = String.valueOf(password.getPassword()).trim();
                    String dataPswConfrim = String.valueOf(passwordConfirm.getPassword());
                    String dataAdminToken = adminToken.getText().trim();
                    int lvl = Constants.LVL_USR_COMMON;//普通用户

                    boolean conditionNull = dataUsername.equals("") || dataPsw.equals("") || dataPswConfrim.equals("");
                    if (conditionNull)
                    {
                        JOptionPane.showMessageDialog(null, "此操作需要输入用户名和密码以及确认密码，请重新输入！", "Error", JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    //判断用户是否已经存在
                    if (JDBCHelper.isUsrExist(dataUsername, JDBCHelper.selectUsr()))
                    {
                        JOptionPane.showMessageDialog(null, "检测到用户已经存在，请重新注册。", "Tip", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    //判断密码和确认密码是否相同
                    if (!dataPsw.equals(dataPswConfrim))
                    {
                        JOptionPane.showMessageDialog(null, "两次密码输入不一致。", "Error", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    if (dataAdminToken.equals(Constants.TOKEN))
                        lvl = Constants.LVL_USR_ADMIN;//改为管理员
                    else if (dataAdminToken.equals(""))
                        lvl = Constants.LVL_USR_COMMON;
                    else
                    {
                        JOptionPane.showMessageDialog(null, "检测到管理员Token错误，请重新输入。", "Tip", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    User usr = new User(dataUsername, dataPsw, lvl, 0.0);//开户
                    JDBCHelper.registryUsr(usr);//添加进数据库
                }
            }
        });

        btnLogin.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                String dataUsername = filedUsername.getText().trim();
                String dataPassword = String.valueOf(fieldPsw.getPassword());
                ArrayList<User> dataUsrs = JDBCHelper.selectUsr();

                //输入合法性判断
                if (dataUsername.equals("") && dataPassword.equals(""))
                {
                    JOptionPane.showMessageDialog(null, "请输入用户名和密码！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                if (dataUsername.equals(""))
                {
                    JOptionPane.showMessageDialog(null, "请输入用户名！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                if (dataPassword.equals(""))
                {
                    JOptionPane.showMessageDialog(null, "请输入密码！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                if (!JDBCHelper.isPwsCorrect(dataUsername, dataPassword, dataUsrs))
                {
                    JOptionPane.showMessageDialog(null, "账户或密码输入错误！", "提示", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }
                User currentUsr = null;
                //搜索该用户实例以获得用户信息
                for (int i = 0; i < dataUsrs.size(); i++)
                {
                    if (dataUsrs.get(i).getUsrname().equals(dataUsername))
                    {
                        currentUsr = dataUsrs.get(i);
                        break;
                    }
                }
                //根据lvl进入界面
                if (JDBCHelper.isAdministrator(currentUsr))
                {
                    new GuiAdmin().showGui();
                }
                else
                {
                    new GuiUser(currentUsr).showGui();
                }
                Main.consoleLog("登录成功。");
                dispose();
            }
        });
    }
}
